package com.example.springbootServiceNetwork.demos.web.Tool;

import com.alibaba.fastjson.JSONObject;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler)throws Exception{
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String token = request.getHeader("Authorization");
        if(token != null){
            boolean result = JwtUtil.verifyToken(token);
            if(result){
               // System.out.println("通过拦截器");
                return true;
            }
        }
        try{
            JSONObject json = new JSONObject();
            json.put("msg","token verify fail or parameter error");
            json.put("code","50000");
            json.put("data","token过期或参数错误！");
            byte[] jsonBytes = json.toJSONString().getBytes(StandardCharsets.UTF_8);
            response.getOutputStream().write(jsonBytes);
           // System.out.println("认证失败，未通过拦截器");

        }catch (Exception e){
            e.fillInStackTrace();
            response.sendError(500);
            return false;
        }
        return false;
    }
}
